package booyah.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang.StringUtils;
import booyah.service.UserService;
import booyah.application.User;

@Controller
@RequestMapping("/createaccount")
public class CreateAccountController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields(new String[] {"id"});
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(Model model) {
        User person = new User();
        model.addAttribute("person", person);
        return "createAccount";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("person") User person, BindingResult result) {
        if (StringUtils.isBlank(person.getEmail())) {
            result.rejectValue("email", "required", "Required");
        }
        if (StringUtils.isBlank(person.getPassword())) {
            result.rejectValue("password", "required", "Required");
        }

        if (!result.hasErrors()) {
            userService.createPerson(person);

        }

        return result.hasErrors() ? "createAccount" : "redirect:login";
    }

}
